package com.team.vlog_temp.Service.Impl;

import com.team.vlog_temp.Dao.MeuDao;
import com.team.vlog_temp.dto.OriginalData;
import com.team.vlog_temp.dto.TreeDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TreeServiceImpl {
    public List<TreeDto> convertToTreeDto(List<Map<String, Object>> departMentlist) {
        List<TreeDto> tree = new ArrayList<>();
        Map<Integer, TreeDto> map = new HashMap<>();

        // 首先将所有节点放入 map 中
        for (Map<String, Object> item : departMentlist) {
            int id = (int) item.get("id");
            String label = (String) item.get("lable"); // 注意这里的拼写是 "lable"
            TreeDto node = new TreeDto(id, label);
            map.put(id, node);
        }

        // 然后构建树结构
        for (Map<String, Object> item : departMentlist) {
            int fatherNum = (int) item.get("fatherNum");
            if (fatherNum == 0) {
                // 根节点
                tree.add(map.get(item.get("id")));
            } else {
                // 子节点
                TreeDto parentNode = map.get(fatherNum);
                if (parentNode != null) {
                    parentNode.getChildren().add(map.get(item.get("id")));
                }
            }
        }

        return tree;
    }
}
